import { open } from "@tauri-apps/plugin-dialog";
import { css } from "styled-system/css";
import {
  Avatar,
  Button,
  Field,
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableHeaderCell,
  TableRow,
  Toast,
  Toaster,
  ToastTitle,
  useId,
  useToastController,
} from "@fluentui/react-components";
import { DatePicker } from "@fluentui/react-datepicker-compat";
import { FLUENT_DATE_PICKER_STRINGS } from "@/utils";
import dayjs from "dayjs";
import { SeasonSelect } from "./components/SeasonSelect";
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { invoke } from "@tauri-apps/api/core";

function App() {
  const toasterId = useId("toaster");
  const { dispatchToast } = useToastController(toasterId);

  const [loadingState, setLoadingState] = useState<LoadingState>("initial");
  const [season, setSeason] = useState<string>();
  const [beginDate, setBeginDate] = useState<Date | null | undefined>(
    dayjs().add(-1, "day").toDate(),
  );

  const { data, refetch } = useQuery({
    queryKey: ["contest.registers"],
    async queryFn() {
      if (season === "") {
        return [];
      }

      let _beginDate = beginDate ? dayjs(beginDate).format("YYYY-MM-DD") : "";
      const response = await fetch(
        `https://v2.huashan.tv/api/a/contests/registers/_hslj_export_tools?season_id=${season || ""}&begin_date=${_beginDate}&end_date=`,
      );
      const data = await response.json();
      return data;
    },
  });

  const items = useMemo(() => data || [], [data]);

  const status = (v: any) => {
    if (v === 2) {
      return "审核中";
    }
    if (v === 6) {
      return "拒绝";
    }
    if (v === 7) {
      return "淘汰";
    }
    return "比赛中";
  };

  const exportData = async () => {
    if (!data || data.length <= 0) {
      dispatchToast(
        <Toast>
          <ToastTitle>没有可导出数据</ToastTitle>
        </Toast>,
        { intent: "error" },
      );
      return;
    }

    const selectedDir = await open({
      directory: true,
    });

    setLoadingState("loading");
    await invoke("export_data", {
      target_dir: selectedDir,
      data: JSON.stringify(data),
    });
    setLoadingState("initial");

    dispatchToast(
      <Toast>
        <ToastTitle>数据导出成功</ToastTitle>
      </Toast>,
      {
        intent: "success",
      },
    );
  };

  return (
    <div
      className={css({
        display: "flex",
        flexDirection: "column",
        gap: "6",
      })}
    >
      <Toaster toasterId={toasterId} />
      <div
        className={css({
          pl: "4",
        })}
      >
        <Field label="赛季">
          <SeasonSelect
            defaultChecked={false}
            onChange={(_, d) => setSeason(d.value)}
          />
        </Field>
        <Field label="开始时间">
          <DatePicker
            value={beginDate}
            strings={FLUENT_DATE_PICKER_STRINGS}
            onSelectDate={(d) => {
              setBeginDate(d);
            }}
            formatDate={(d) => {
              if (d) {
                return dayjs(d).format("YYYY-MM-DD");
              }
              return "";
            }}
          />
        </Field>

        <Button onClick={() => refetch()}>查询</Button>
        <Button
          disabledFocusable={loadingState !== "initial"}
          onClick={() => exportData()}
        >
          导出
        </Button>
      </div>

      <Table style={{ minWidth: "510px" }}>
        <TableHeader>
          <TableRow>
            <TableHeaderCell>报名时间</TableHeaderCell>
            <TableHeaderCell>赛季</TableHeaderCell>
            <TableHeaderCell>门派</TableHeaderCell>
            <TableHeaderCell>赛区</TableHeaderCell>
            <TableHeaderCell>掌门</TableHeaderCell>
            <TableHeaderCell>教练</TableHeaderCell>
            <TableHeaderCell>领队</TableHeaderCell>
            <TableHeaderCell>状态</TableHeaderCell>
          </TableRow>
        </TableHeader>
        <TableBody>
          {items.map((item: any) => (
            <TableRow>
              <TableCell>
                {dayjs(item.create_time).format("YYYY-MM-DD")}
              </TableCell>
              <TableCell>{item.season_id}</TableCell>
              <TableCell>
                <Avatar
                  image={{
                    src: `${item.logo}?x-oss-process=image%2Fresize%2Cm_fixed%2Cw_150%2Ch_150`,
                  }}
                />
                {item.sect_name}
              </TableCell>
              <TableCell>{item.zone_id}</TableCell>
              <TableCell>
                <Avatar
                  image={{
                    src: `${item.chief.avatar}?x-oss-process=image%2Fresize%2Cm_fixed%2Cw_150%2Ch_150`,
                  }}
                />
                {item.chief.name}
              </TableCell>
              <TableCell>
                <Avatar
                  image={{
                    src: `${item.coach.avatar}?x-oss-process=image%2Fresize%2Cm_fixed%2Cw_150%2Ch_150`,
                  }}
                />
                {item.coach.name}
              </TableCell>
              <TableCell>
                <Avatar
                  image={{
                    src: `${item.leader.avatar}?x-oss-process=image%2Fresize%2Cm_fixed%2Cw_150%2Ch_150`,
                  }}
                />
                {item.leader.name}
              </TableCell>
              <TableCell>{status(item.status)}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}

export default App;
